#include <mysql/mysql.h>
#include <iostream>

using std::string;

int main() {
    MYSQL *conn;
    MYSQL_RES *res;
    MYSQL_ROW row;

    conn = mysql_init(NULL);

    if (!mysql_real_connect(conn, "127.0.0.1", "mainuser", "Bu1.buqi", "userdb", 0, NULL, 0)) {
        std::cerr << "Error connecting to database: " << mysql_error(conn) << std::endl;
        mysql_close(conn);
        return 1;
    }



    string table="users";
    string key="(username, email)";
    string value="('yy','yy@qq.com')";
    string wherekey="username";
    string wherevalue="(username)";


    string sqlcmdline = string("INSERT INTO ")+table+string(" ")+key +string(" VALUES ") + value+ " ON DUPLICATE KEY UPDATE "+ wherekey+ " = VALUES "+ wherevalue;
    if (mysql_query(conn, sqlcmdline.c_str())) {
        std::cerr << "Error querying data: " << mysql_error(conn) << std::endl;
        mysql_close(conn);
        return 1;
    }

    // 插入数据
    if (mysql_query(conn, "INSERT INTO users (username, email) VALUES ('Xiao gang', 'gang@example.com')")) {
        std::cerr << "Error inserting data: " << mysql_error(conn) << std::endl;
        mysql_close(conn);
        return 1;
    }

    // 查询数据
    if (mysql_query(conn, "SELECT * FROM users")) {
        std::cerr << "Error querying data: " << mysql_error(conn) << std::endl;
        mysql_close(conn);
        return 1;
    }

    res = mysql_store_result(conn);
    while ((row = mysql_fetch_row(res))) {
        std::cout << "ID: " << row[0] << ", Name: " << row[1]
                  << ", Email: " << row[2] << std::endl;
    }
    mysql_free_result(res);

    // 删除数据
    if (mysql_query(conn, "DELETE FROM users WHERE username = 'John Doe'")) {
        std::cerr << "Error deleting data: " << mysql_error(conn) << std::endl;
        mysql_close(conn);
        return 1;
    }

    mysql_close(conn);

    return 0;
}
